# -*- coding: utf-8 -*-
# =============================================================================
#     FileName:
#         Desc:
#       Author: GGA
#        Email:
#     HomePage:
#      Version: 1.0.1
#   LastChange: 2020-12-20
#      History:
# =============================================================================
import re
import datetime


class MySQLBinlogParser(object):
    DML_ACTION_PREFIXES = ["### INSERT INTO", "### UPDATE", "### DELETE FROM"]

    @classmethod
    def parse_binlog_pos(cls, binlog_line):
        if binlog_line.find("# at") >= 0:
            return int(binlog_line.replace("# at", "").strip())
        return None

    @classmethod
    def parse_binlog_datetime(cls, binlog_line):
        """
        解析记录行中包含的时间
        :param binlog_line:
        :return:
        """
        matches = re.findall(r'\d{6}\s\d{2}:\d{2}:\d{2}', binlog_line)
        if matches:
            dt_str = "20" + matches[0]
            return datetime.datetime.strptime(dt_str, "%Y%m%d %H:%M:%S")
        return None

    @classmethod
    def parse_table_column_line(cls, binlog_line: str):
        """
        解析DML语句的每行记录，拆分列坐标和列对应的值
        :param binlog_line:
        :return:
        """
        if binlog_line.find("###   @") < 0:
            return
        binlog_line = binlog_line.replace("###   @", '')
        char_index = binlog_line.index("=")
        column_index = int(binlog_line[0:char_index])
        column_value = binlog_line[char_index + 1:].strip()
        return column_index, column_value

    @classmethod
    def parse_table_name_line(cls, binlog_lin: str):
        """
        将包含有 INSERT/UPDATE/DELETE的行解析返回表名
        :param binlog_lin:
        :return:
        """
        for dml_action_prefix in cls.DML_ACTION_PREFIXES:
            if binlog_lin.startswith(dml_action_prefix):
                return dml_action_prefix.replace(dml_action_prefix, "").strip()
        return None
